package service.impl;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import model.Admin;
import service.IAdminService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by ykj on 16/1/7.
 */
public class AdminServiceImpl implements IAdminService {

    public Set<String> findAllTables() {
        List<Record> records = Db.find("select TABLE_NAME from information_schema.COLUMNS where table_schema = 'financial'");
        Set<String> set = new HashSet<String>();
        for (Record record : records) {
            set.add(record.getStr("TABLE_NAME"));
        }
        return set;
    }

    public List<String> findColumnsByTable(String tableName) {
        List<Record> records = Db.find("select COLUMN_NAME from information_schema.COLUMNS where table_name = ? and table_schema = 'financial'", tableName);
        List<String> columns = new ArrayList<String>();
        for (Record record : records) {
            columns.add(record.getStr("COLUMN_NAME"));
        }
        return columns;
    }

    public Admin login(String username, String password) {
        Admin admin = Admin.dao.findFirst("select * from admin where name = ? and pwd = ?", username, password);
        return admin;
    }

    public Page findByPage(int page, int pageSize) {
        return Admin.dao.paginate(page, pageSize, "select * from admin");
    }

    public Model save(Model model) {
        Admin admin = (Admin) model;
        Long exists = Db.queryLong("select 1 from admin where name = ?", admin.getName());
        //已存在相同记录
        if(exists != null) return null;
        boolean result = admin.save();
        return result ? admin : null;
    }

    public Model update(Model model) {
        Admin admin = (Admin) model;
        boolean result = admin.update();
        return result ? admin : null;
    }

    public boolean delete(int id) {
        return Admin.dao.deleteById(id);
    }

    public Model findById(int id) {
        return Admin.dao.findById(id);
    }
}
